/**
 * created by 小卷毛, 2020/9/16
 * Copyright (c) 2020, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.cepri.service.yingxiao;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.text.TextUtils;

import com.sgcc.pda.lib_record_voice_v7.AudioRecorder;
import com.sgcc.pda.lib_record_voice_v7.FileUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 描 述：录音和播放管理类
 * 作 者：小卷毛  2020-09-16 11:45
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
public class MediaPlayerManager {

    private MediaPlayer mediaPlayer;
    private AudioRecorder mRecorder;

    private String fileName;
    private String audioType;
    private boolean isAudioPlaying;

    private Timer mTimer; //计时器
    private long mDuration = 0;
    private TimeStateListener listener;

    /**
     * 类级的内部类，也就是静态类的成员式内部类，该内部类的实例与外部类的实例
     * 没有绑定关系，而且只有被调用时才会装载，从而实现了延迟加载
     */
    private static class MediaPlayerManagerHolder {
        /**
         * 静态初始化器，由JVM来保证线程安全
         */
        private static MediaPlayerManager instance = new MediaPlayerManager();
    }

    public static MediaPlayerManager getInstance() {
        return MediaPlayerManagerHolder.instance;
    }

    private MediaPlayerManager() {
        mRecorder = AudioRecorder.getInstance();
        mediaPlayer = new MediaPlayer();
    }

    /**
     * 开始录音
     */
    @SuppressLint("SimpleDateFormat")
    public void record() {
        if (isAudioPlaying) {
            stopPlay();
        }

        fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        mRecorder.createDefaultAudio(fileName);
        mRecorder.startRecord(null);

        audioType = "record";
        startTimer();
    }

    /**
     * 停止录音
     */
    public void stopRecord() {
        mRecorder.stopRecord();

        cancelTimer();
        mDuration = 0;

        if (listener != null) {
            listener.onDone(audioType, getFilePath());
        }
    }

    /**
     * 暂停录音
     */
    public void pauseRecord() {
        mRecorder.pauseRecord();

        cancelTimer();
    }

    /**
     * 取消录音
     */
    public void cancleRecord() {
        mRecorder.cancel();

        cancelTimer();
        mDuration = 0;
        fileName = "";
    }

    /**
     * 初始化播放
     */
    private void prepareAudio() {
        try {
            mediaPlayer.setDataSource(FileUtil.getWavFileAbsolutePath(fileName));
            // 设置循环播放
            mediaPlayer.setLooping(false);
            mediaPlayer.prepare();

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlay();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化播放
     */
    private void prepareAudio(String filePath) {
        try {
            mediaPlayer.setDataSource(filePath);
            // 设置循环播放
            mediaPlayer.setLooping(false);
            mediaPlayer.prepare();

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlay();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 录音播放
     */
    public void play() {
        if (TextUtils.isEmpty(fileName)
                || mRecorder.getStatus() == AudioRecorder.Status.STATUS_START
                || mRecorder.getStatus() == AudioRecorder.Status.STATUS_PAUSE) return;

        if (!isAudioPlaying) {
            prepareAudio();
            isAudioPlaying = true;
        }

        mediaPlayer.start();

        audioType = "play";
        startTimer();
    }


    /**
     * 录音播放
     */
    public void play(String file) {
        if (TextUtils.isEmpty(file)
                || mRecorder.getStatus() == AudioRecorder.Status.STATUS_START
                || mRecorder.getStatus() == AudioRecorder.Status.STATUS_PAUSE) return;

        if (!isAudioPlaying) {
            prepareAudio(file);
            isAudioPlaying = true;
        }

        mediaPlayer.start();

        audioType = "play";
        startTimer();
    }

    /**
     * 暂停播放
     */
    public void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();

            cancelTimer();
        }
    }

    /**
     * 停止播放
     */
    public void stopPlay() {
        if (mediaPlayer != null) {
            isAudioPlaying = false;
            mediaPlayer.stop();
            mediaPlayer.reset();

            cancelTimer();
            mDuration = 0;

            if (listener != null) {
                listener.onDone(audioType, getFilePath());
            }
        }
    }

    /**
     * 开始计时
     */
    private void startTimer() {
        cancelTimer();

        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mDuration += 1;
                if (listener != null) {
                    listener.onTick(audioType, mDuration);
                }
            }
        }, 1000, 1000);

        if (listener != null) {
            listener.onTick(audioType, mDuration);
        }
    }

    /**
     * 停止计时
     */
    private void cancelTimer() {
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

    /**
     * 获取文件路径，录音停止后获取
     */
    public String getFilePath() {
        return FileUtil.getWavFileAbsolutePath(fileName);
    }

    public void setTimeListener(TimeStateListener listener) {
        this.listener = listener;
    }

    /**
     * 计时状态监听
     */
    public interface TimeStateListener {
        /**
         * 计时时长，每秒触发
         *
         * @param type        record录音，play播放
         * @param millisecond 秒
         */
        void onTick(String type, long millisecond);

        /**
         * 计时结束回调
         *
         * @param type record录音，play播放
         * @param path 文件保存路径
         */
        void onDone(String type, String path);
    }

}
